<template>
  <div class="action-menu">
    <template v-for="(action, idx) in primaryActions" :key="idx">
      <el-button type="text" size="small" @click="action.onClick" :disabled="action.disabled">
        {{ action.label }}
      </el-button>
    </template>
    <el-dropdown v-if="showDropdown && moreActions.length" trigger="click" @command="onCommand">
      <el-button class="more-btn" link type="primary" size="small">
        更多 <el-icon><ArrowDown /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="(m, i) in moreActions" :key="i" :command="i" :disabled="m.disabled">
            {{ m.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'

interface MenuAction {
  label: string
  onClick: () => void
  disabled?: boolean
}

const props = defineProps<{
  actions: MenuAction[]
  primaryCount?: number
}>()

const emit = defineEmits<{ (e: 'select', index: number): void }>()

const showDropdown = computed(() => (props.actions?.length || 0) > 3)
const effectivePrimaryCount = computed(() => showDropdown.value ? (props.primaryCount ?? 2) : props.actions.length)

const primaryActions = computed(() => props.actions.slice(0, effectivePrimaryCount.value))
const moreActions = computed(() => showDropdown.value ? props.actions.slice(effectivePrimaryCount.value) : [])

const onCommand = (index: number) => {
  const action = moreActions.value[index]
  if (action) action.onClick()
  emit('select', index)
}
</script>

<style scoped>
.action-menu {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
.more-btn :deep(span) {
  display: inline-flex;
  align-items: center;
}
</style> 